import { defineStore } from 'pinia'
import { locationApi } from '@/api'

export const useLocationStore = defineStore('location', {
  state: () => ({
    // 地点列表
    locationList: [],
    // 搜索结果
    searchResults: [],
    // 当前选择的地点
    selectedLocation: null,
    // 加载状态
    loading: false,
    // 搜索关键词
    searchKeyword: ''
  }),

  getters: {
    // 获取地点总数
    totalLocations: (state) => state.locationList.length,

    // 获取搜索结果
    searchResultList: (state) => state.searchResults,

    // 根据ID获取地点
    getLocationById: (state) => (id) => {
      return state.locationList.find(location => location.id === id)
    },

    // 根据名称搜索地点
    getLocationByName: (state) => (name) => {
      return state.locationList.find(location =>
        location.name.toLowerCase().includes(name.toLowerCase())
      )
    }
  },

  actions: {
    // 获取地点列表
    async getLocationList(params = {}) {
      try {
        this.loading = true
        const response = await locationApi.getLocationList(params)

        if (response.code === 200) {
          this.locationList = response.data.list || []
        }
      } catch (error) {
        console.error('获取地点列表失败:', error)
        this.locationList = []
      } finally {
        this.loading = false
      }
    },

    // 搜索地点
    async searchLocation(keyword) {
      try {
        this.loading = true
        this.searchKeyword = keyword

        if (!keyword.trim()) {
          this.searchResults = []
          return
        }

        const response = await locationApi.searchLocation(keyword)

        if (response.code === 200) {
          this.searchResults = response.data || []
        }
      } catch (error) {
        console.error('搜索地点失败:', error)
        this.searchResults = []
      } finally {
        this.loading = false
      }
    },

    // 添加地点
    async addLocation(locationData) {
      try {
        this.loading = true
        const response = await locationApi.addLocation(locationData)

        if (response.code === 200) {
          // 添加到列表
          this.locationList.unshift(response.data)
          return { success: true, data: response.data, message: '添加成功' }
        } else {
          return { success: false, message: response.message || '添加失败' }
        }
      } catch (error) {
        console.error('添加地点失败:', error)
        return { success: false, message: error.message || '添加失败' }
      } finally {
        this.loading = false
      }
    },

    // 设置选择的地点
    setSelectedLocation(location) {
      this.selectedLocation = location
    },

    // 清除选择的地点
    clearSelectedLocation() {
      this.selectedLocation = null
    },

    // 清除搜索结果
    clearSearchResults() {
      this.searchResults = []
      this.searchKeyword = ''
    }
  }
})
